<template>
  <div id="order">
    <div class="order-top">
      <div class="form-group">
        <span class="spanRed">*</span>供应商：
        <el-input
          style="width: 150px"
          v-model="purchaseOrder.proName"
        ></el-input>
        <el-button @click="dialogShow = true">...</el-button>
      </div>

      <div class="form-group">
        业务员：
        <el-select
          v-model="purchaseOrder.yid"
          placeholder="业务员"
          style="margin-left: 10px; width: 100px"
        >
          <el-option label="(空)" :value="0"> </el-option>
          <el-option
            v-for="item in employee"
            :key="item.employeeId"
            :label="item.employeeName"
            :value="item.employeeId"
          >
          </el-option>
        </el-select>
      </div>

      <!-- <div class="form-group">
        供应商发货地址:
        <el-select
          v-model="value"
          placeholder="供应商发货地址"
          style="margin-left: 10px; width: 150px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div> -->

      <div class="form-group">
        交货方式:
        <el-select
          v-model="purchaseOrder.deliveryMethodId"
          placeholder="交货方式"
          style="margin-left: 10px; width: 110px"
        >
          <el-option label="(空)" :value="0"> </el-option>
          <el-option label="快递物流" :value="1"> </el-option>
          <el-option label="自配送" :value="2"> </el-option>
          <el-option label="自提" :value="3"> </el-option>
          <el-option label="其他" :value="4"> </el-option>
        </el-select>
      </div>

      <div class="form-group">
        <span class="demonstration">单据日期:</span>
        <el-date-picker
          v-model="purchaseOrder.createDate"
          align="right"
          type="date"
          placeholder="选择日期"
          style="margin-left: 10px"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </div>

      <div class="form-group">
        <i class="el-icon-paperclip" style="color: blue"></i>
        <span style="color: blue">上传附件</span>
        <span style="margin-left: 10px">单据编号:</span>
        <el-input
          style="width: 120px; margin-left: 10px; margin-right: 20px"
          placeholder=""
          v-model="purchaseOrder.documentNumber"
          clearable
          disabled
        >
        </el-input>
        <el-dropdown>
          <span class="el-dropdown-link">
            <i class="el-icon-edit"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>XHD</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <el-dialog top="20px" title="选择供应商" :visible.sync="dialogShow">
      <ProviderChoose ref="choosePro" :dialogShow="dialogShow" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="yes">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog top="20px" title="选择商品" :visible.sync="goodsShow">
      <GoodsChoose ref="chooseGoods" :goodsShow="goodsShow" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="goodsShow = false">取 消</el-button>
        <el-button type="primary" @click="yesGoods">确 定</el-button>
      </div>
    </el-dialog>

    <el-divider></el-divider>
    <div style="float: right; margin-bottom: 10px">
      <!-- <el-button>保存并新增</el-button> -->

      <el-button
        v-if="
          purchaseOrder.reviewStatus == 0 || purchaseOrder.reviewStatus == ''
        "
        type="primary"
        @click="save()"
        >保存{{ this.purchaseOrder.id ? "修改" : "新增" }}</el-button
      >
      <el-button
        type="primary"
        v-if="
          purchaseOrder.reviewStatus == 0 || purchaseOrder.reviewStatus == ''
        "
        @click="git()"
        >提交</el-button
      >
      <el-button type="primary">导入</el-button>
      <el-button
        type="success"
        v-if="taskId && purchaseOrder.reviewStatus == 1"
        @click="audit()"
        >审核</el-button
      >
      <el-button
        type="warning"
        v-if="purchaseOrder.reviewStatus == 2"
        @click="reverseAudit()"
        >反审核</el-button
      >
    </div>

    <div class="order-content">
      <el-table
        :row-style="{ height: '55px' }"
        :data="purchaseOrderDetail"
        height="330px"
        border
        style="width: 100%; font-size: 13px; margin-left: 20px"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column style="width: 120px; padding-left: 10px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              style="margin-left: 10px"
              @click="addRow(scope.$index)"
              ><i class="el-icon-circle-plus-outline"></i
            ></el-button>
            <el-button size="mini" @click="reduceRow(scope.$index)"
              ><i class="el-icon-remove-outline"></i
            ></el-button>
          </template>
        </el-table-column>

        <el-table-column prop="goodcode" label="商品编号" width="300">
          <template slot="header" slot-scope="{ column }">
            <span class="spanRed">*</span> {{ column.label }}
          </template>
          <template slot-scope="scope">
            <el-input
              style="width: 200px"
              placeholder="商品"
              v-model="scope.row.goodcode"
            ></el-input
            ><el-button @click="goods(scope.$index)">选择</el-button>
          </template>
        </el-table-column>

        <el-table-column prop="goodname" label="商品名称" width="150">
          <template slot-scope="scope">
            <el-input size="small" v-model="scope.row.goodname"></el-input>
          </template>
        </el-table-column>

        <el-table-column prop="imagename" label="商品图片" width="120">
        </el-table-column>
        <el-table-column prop="categoryName" label="商品类别" width="120">
        </el-table-column>
        <el-table-column prop="brandName" label="品牌" width="120">
        </el-table-column>
        <el-table-column prop="unitname" label="单位" width="120">
        </el-table-column>

        <!-- 仓库 -->
        <el-table-column prop="" label="仓库" width="320">
          <template slot="header" slot-scope="{ column }">
            <span class="spanRed">*</span> {{ column.label }}
          </template>
          <template slot-scope="scope">
            <!-- <el-button
              slot="append"
              icon="el-icon-search"
              @click="dialogVisible3 = true"
            ></el-button> -->

            <el-select v-model="scope.row.wId" placeholder="请选择">
              <el-option
                v-for="item in storeHouse"
                :key="item.shId"
                :label="item.storeHomeCode + ' ' + item.storeHomeName"
                :value="item.shId"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>

        <!-- 可用库存 -->
        <el-table-column prop="availableStock" label="可用库存" width="120">
          <template slot-scope="scope">
            {{ scope.row.availableStock }}
          </template>
        </el-table-column>

        <!-- 数量 -->
        <el-table-column label="数量" width="130">
          <template slot="header" slot-scope="{ column }">
            <span class="spanRed">*</span> {{ column.label }}
          </template>
          <template slot-scope="scope">
            <el-input
              style="width: 100px"
              placeholder="数量"
              v-model="scope.row.totalNum"
              @blur="calculateRow(scope.row)"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column label="购货订单剩余可生成数量" width="130">
          <template slot-scope="scope">
            {{ scope.row.maxTotalNum }}
          </template>
        </el-table-column>

        <!-- 整件散包 -->
        <el-table-column prop="packType" label="整件散包" width="120">
        </el-table-column>

        <!-- 基本单位 -->
        <el-table-column prop="unitname" label="基本单位" width="120">
        </el-table-column>

        <!-- 基本数量 -->
        <el-table-column prop="totalNum" label="基本数量" width="120">
          <template slot-scope="scope">
            {{ scope.row.totalNum }}
          </template>
        </el-table-column>

        <!-- 购货单价 -->
        <el-table-column prop="purchasePrice" label="购货单价" width="130">
          <template slot-scope="scope">
            <el-input
              style="width: 100px"
              placeholder="购货单价"
              v-model="scope.row.purchasePrice"
              @blur="calculateRow(scope.row)"
            ></el-input>
          </template>
        </el-table-column>

        <!-- 含税单价 -->
        <el-table-column prop="totalPrice" label="含税单价" width="120">
          <template slot-scope="scope">
            <el-input
              style="width: 90px"
              placeholder="含税单价"
              v-model="scope.row.totalPrice"
              @blur="calculateRowTotalPrice(scope.row)"
            ></el-input>
          </template>
        </el-table-column>

        <!-- 折扣率 -->
        <el-table-column prop="discount" label="折扣率(%)" width="120">
          <template slot-scope="scope">
            <el-input
              style="width: 90px"
              placeholder="折扣率"
              v-model="scope.row.discount"
              @blur="calculateRow(scope.row)"
            ></el-input>
          </template>
        </el-table-column>

        <!-- 折扣 -->
        <el-table-column prop="discountNoRate" label="折扣(折)" width="120">
          <template slot-scope="scope">
            <el-input
              style="width: 90px"
              placeholder="折扣"
              v-model="scope.row.discountNoRate"
              @blur="calculateDiscountNoRate(scope.row)"
            ></el-input>
          </template>
        </el-table-column>

        <!-- 折扣额 -->
        <el-table-column prop="discountAmount" label="折扣额" width="120">
          <template slot-scope="scope">
            <el-input
              style="width: 90px"
              placeholder="商品"
              v-model="scope.row.discountAmount"
              @blur="calculateRowDiscountAmount(scope.row)"
            ></el-input>
          </template>
        </el-table-column>

        <!-- 金额 -->
        <el-table-column prop="amount" label="金额" width="120">
          <template slot-scope="scope">
            <el-input
              style="width: 90px"
              placeholder="商品"
              v-model="scope.row.amount"
              @blur="calculateRowAmount(scope.row)"
            ></el-input>
          </template>
        </el-table-column>

        <!-- 税率 -->
        <el-table-column label="税率(%)" width="120">
          <template slot-scope="scope">
            <el-input
              style="width: 90px"
              placeholder="税率"
              v-model="scope.row.taxRate"
              @blur="calculateRow(scope.row)"
            ></el-input>
          </template>
        </el-table-column>

        <!-- 税额 -->
        <el-table-column prop="tax" label="税额" width="120">
          <template slot-scope="scope">
            <el-input
              style="width: 90px"
              placeholder="税额"
              v-model="scope.row.tax"
              @blur="calculateRowTax(scope.row)"
            ></el-input>
          </template>
        </el-table-column>

        <!-- 价税合计 -->
        <el-table-column prop="totalMoney" label="价税合计" width="120">
          <template slot-scope="scope">
            <el-input
              style="width: 90px"
              placeholder="价税合计"
              v-model="scope.row.totalMoney"
              @blur="calculateRowTotalMoney(scope.row)"
            ></el-input>
          </template>
        </el-table-column>

        <!-- 采购费用 -->
        <el-table-column prop="purPri" label="采购费用" width="120">
          <template slot-scope="scope">
            <el-input
              style="width: 90px"
              placeholder="采购费用"
              v-model="scope.row.purPri"
            ></el-input>
          </template>
        </el-table-column>

        <!-- 备注 -->
        <el-table-column label="备注" width="120">
          <template slot-scope="scope">
            <el-input
              style="width: 90px"
              placeholder="备注"
              v-model="scope.row.detailRemark"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column prop="relatedOrder" label="关联购货订单号" width="230">
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-input
        type="textarea"
        placeholder="备注"
        rows="2"
        v-model="purchaseOrder.remark"
        style="width: 100%; margin: 10px 0 0 10px"
      >
      </el-input>
    </div>

    <div class="return" style="">
      本次付款：
      <el-input
        style="width: 200px; margin-left: 10px; margin-right: 20px"
        v-model="purchaseOrder.thisPayment"
        clearable
      >
      </el-input>
      总欠款：
      <el-input
        style="width: 80px; margin-left: 10px; margin-right: 20px"
        placeholder=""
        v-model="totalAmountsOwed"
        clearable
        disabled
      >
      </el-input>

      本次欠款：
      <el-input
        style="width: 80px; margin-left: 10px; margin-right: 20px"
        placeholder=""
        :value="purchaseOrder.amount - purchaseOrder.thisPayment"
        clearable
        disabled
      >
      </el-input>

      采购费用：
      <el-input
        style="width: 80px; margin-left: 10px; margin-right: 20px"
        placeholder=""
        v-model="purchaseOrder.purPriSum"
        clearable
        disabled
      >
      </el-input>
      <!-- <el-button @click="dialogVisible4 = true">...</el-button>
      <el-button>采购销售费用清单</el-button> -->

      结算方式：
      <el-select
        v-model="purchaseOrder.accountId"
        placeholder="结算账户"
        style="width: 200px"
      >
        <el-option
          v-for="item in accounts"
          :key="item.accountId"
          :label="item.accountCode + '' + item.accountName"
          :value="item.accountId"
        >
        </el-option>
      </el-select>
    </div>

    <div style="float: right; margin-top: 10px">
      <el-button @click="goto('PurOrdDoc')">历史单据</el-button>
    </div>
  </div>
</template>

<script>
import ProviderChoose from "../public_com/ProviderChoose.vue";
import GoodsChoose from "../public_com/GoodsChoose.vue";
import { myMixin } from "./other/mixin.js";

export default {
  name: "purchaseOrder",
  components: {
    ProviderChoose,
    GoodsChoose,
  },
  mixins: [myMixin],
  data() {
    return {
      taskId: "",
      totalAmountsOwed: "",
      dialogShow: "",
      employee: [],
      dialogShow: false,
      goodsShow: false,
      storeHouse: [],
      selectByIdDate: [],
      purchaseOrder: {
        id: "",
        proId: "",
        yid: "",
        accountId: "",
        deliveryMethodId: "",
        createDate: "",
        purPriSum: 0, //采购费用
        thisPayment: 0, //本次付款
        quantity: "",
        amount: "",
        status: "",
        remark: "",
        documentNumber: "",
        //已核销金额
        //
        proName: "",
        purType: 1,
        //购货单生成购货订单
        orderNumber: "", //关联购货订单号
        reviewStatus: "",
      },
      purchaseOrderDetail: [
        {
          id: "", // id
          numbering: "", // 购货单id
          unitId: "", // 单位Id
          totalNum: 1, // 数量
          maxTotalNum: "",
          discount: 0, // 折扣率
          detailRemark: "", // 详细备注
          imagename: null, // 商品图片名称
          goodcode: "", // 商品编号
          brandName: "", // 品牌名称
          origin: "", // 产地
          goodname: "", // 商品名称
          categoryName: "", // 商品类别
          unitname: "", // 单位名称
          wId: "", // 仓库Id
          availableStock: "", // 可用库存
          purchasePrice: 0, //购货单价
          totalPrice: 0, // 含税单价
          taxRate: 0, // 税率
          tax: 0, // 税额
          totalMoney: 0, // 价税合计
          discountAmount: 0, // 折扣额
          discountNoRate: 10, // 折扣(折)
          amount: 0, // 金额
          purPri: 0, //采购费用
          relatedOrder: "", //关联购货订单
          orderDetailId: "",
        },
      ],
      accounts: [],
      orderId: "",
    };
  },
  watch: {
    "purchaseOrder.proId": function (newVal, oldVal) {
      if (newVal !== oldVal) {
        this.handleProIdChange(newVal);
      }
    },
  },
  methods: {
    handleProIdChange(newProId) {
     if(newProId){
        this.axios
        .get("/info/provider/getProviderById", {
          params: {
            providerId: this.purchaseOrder.proId,
          },
        })
        .then((rs) => {
          this.totalAmountsOwed=rs.data.shouldPay
        });
     }else{
        this.totalAmountsOwed=''
     }
    },
    audit() {
      this.axios
        .get("/purchase/order/competePay", {
          params: {
            taskId: this.taskId,
          },
        })
        .then((rs) => {
          if (rs.data.code == 200) {
            this.successMessage( this.purchaseOrder.documentNumber+"购货单审核成功")
            this.purchaseOrder.reviewStatus=2
          }else{
             this.errorMessage( this.purchaseOrder.documentNumber+"购货单审核失败")
          }
        });
    },
    reverseAudit() {

      

      this.axios
        .get("/purchase/purchaseOrder/reverseAudit", {
          params: {
            documentNumber: this.purchaseOrder.documentNumber,
          },
        })
        .then((rs) => {
          if (rs.data.code == 200) {
            this.successMessage(
              this.purchaseOrder.documentNumber + "购货单反审核成功",
              this.purchaseOrder.reviewStatus=0
            );
          } else {
            this.errorMessage(
              this.purchaseOrder.documentNumber + "购货单反审核失败"
            );
          }
        });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      let validData = data.filter((item) => item.goodcode); // 过滤出商品编码不为空的行

      let totalNum = 0; // 用于累计数量的合计
      let totalMoney = 0; // 用于累计价税合计的合计
      let purPriSum = 0;

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        // 定义需要合计的列属性
        const needSumProperties = [
          "totalNum",
          "discountAmount",
          "amount",
          "tax",
          "totalMoney",
          "purPri",
        ];
        if (needSumProperties.includes(column.property)) {
          const values = validData.map((item) => Number(item[column.property]));
          const sum = values.reduce((prev, curr) => {
            const value = Number(curr);
            return !isNaN(value) ? prev + value : prev;
          }, 0);
          if (column.property === "totalNum") {
            // 数量列，不保留小数点
            totalNum = sum; // 累计数量合计
            sums[index] = sum;
          } else if (column.property === "totalMoney") {
            // 价税合计列，保留两位小数
            totalMoney = sum; // 累计价税合计
            sums[index] = sum.toFixed(2);
          } else if (column.property === "purPri") {
            // 价税合计列，保留两位小数
            purPriSum = sum; // 累计价税合计
            sums[index] = sum.toFixed(2);
          } else {
            // 其他金额列，保留两位小数
            sums[index] = sum.toFixed(2);
          }
        } else {
          sums[index] = "";
        }
      });

      // 将合计的数量和价税合计赋值给purchaseInquiry对象
      this.purchaseOrder.quantity = totalNum.toFixed(0);
      this.purchaseOrder.amount = totalMoney.toFixed(2);
      this.purchaseOrder.purPriSum = purPriSum.toFixed(2);

      return sums;
    },
    git() {
      //数据校验

      // 校验供应商
      if (!this.purchaseOrder.proId) {
        this.errorMessage("供应商不能为空");
        return;
      }

      // 校验单据日期
      if (!this.purchaseOrder.createDate) {
        this.errorMessage("单据日期不能为空");
        return;
      }

      if (this.purchaseOrder.thisPayment > this.purchaseOrder.amount) {
        this.errorMessage("本次付款不能大于价税合计总金额");
        return;
      }

      var msgWId = "";
      var msgTotalNum = "";

      console.log(this.purchaseOrder);
      //获取入库单明细
      var details = [];

      this.purchaseOrderDetail.forEach((inquiry, index) => {
        if (inquiry.goodcode && inquiry.goodname) {
          // 只有当商品编码不为空时，才添加到details

          if (!inquiry.wId) {
            msgWId = "商品" + inquiry.goodcode + "仓库不可以为空";
            return;
          }

          if (inquiry.maxTotalNum && inquiry.totalNum > inquiry.maxTotalNum) {
            msgTotalNum =
              "第" +
              (index + 1) +
              "行商品" +
              inquiry.goodcode +
              "购货单基本数量高于购货订单剩余可生成基本数量，请确认并修改后重试!";
          }

          details.push({
            unitId: inquiry.unitId, //
            totalNum: inquiry.totalNum, //
            purchasePrice: inquiry.purchasePrice,
            discount: inquiry.discount, //
            taxRate: inquiry.taxRate,
            totalMoney: inquiry.totalMoney,
            detailRemark: inquiry.detailRemark, //
            goodcode: inquiry.goodcode, //
            goodname: inquiry.goodname, //
            unitname: inquiry.unitname, //
            wId: inquiry.wId, //
            purPri: inquiry.purPri, //采购费用
            relatedOrder: inquiry.relatedOrder, //关联购货订单
            orderDetailId: inquiry.orderDetailId,
          });
        }
      });

      if (msgWId) {
        this.errorMessage(msgWId);
        return;
      }

      if (msgTotalNum) {
        this.errorMessage(msgTotalNum);
        return;
      }

      if (this.purchaseOrder.thisPayment && !this.purchaseOrder.accountId) {
        this.errorMessage("付款额不为空时，请选择结算账户");
        return;
      }

      if (details.length < 1) {
        this.errorMessage("商品信息不可以为空");
        return;
      }

      // console.log(details)
      const formdata = new FormData();
      formdata.append("purchaseOrder", JSON.stringify(this.purchaseOrder));
      formdata.append("purchaseOrderDetail", JSON.stringify(details));
      formdata.append("git", 1);

      if (!this.purchaseOrder.id) {
        this.axios.post("/purchase/purchaseOrder/add", formdata).then((rs) => {
          if ((rs.data.code = 200)) {
            this.successMessage("添加提交成功");
            this.letNull();
          } else {
            this.errorMessage("添加提交失败");
          }
        });
      } else {
        this.axios
          .post("/purchase/purchaseOrder/update", formdata)
          .then((rs) => {
            if ((rs.data.code = 200)) {
              this.successMessage("修改提交成功");
              this.letNull();
            } else {
              this.errorMessage("修改提交失败");
            }
          });
      }
    },
    save() {
      //数据校验

      // 校验供应商
      if (!this.purchaseOrder.proId) {
        this.errorMessage("供应商不能为空");
        return;
      }

      // 校验单据日期
      if (!this.purchaseOrder.createDate) {
        this.errorMessage("单据日期不能为空");
        return;
      }

      if (this.purchaseOrder.thisPayment > this.purchaseOrder.amount) {
        this.errorMessage("本次付款不能大于价税合计总金额");
        return;
      }

      var msgWId = "";
      var msgTotalNum = "";

      console.log(this.purchaseOrder);
      //获取入库单明细
      var details = [];

      this.purchaseOrderDetail.forEach((inquiry, index) => {
        if (inquiry.goodcode && inquiry.goodname) {
          // 只有当商品编码不为空时，才添加到details

          if (!inquiry.wId) {
            msgWId = "商品" + inquiry.goodcode + "仓库不可以为空";
            return;
          }

          if (inquiry.maxTotalNum && inquiry.totalNum > inquiry.maxTotalNum) {
            msgTotalNum =
              "第" +
              (index + 1) +
              "行商品" +
              inquiry.goodcode +
              "购货单基本数量高于购货订单剩余可生成基本数量，请确认并修改后重试!";
          }

          details.push({
            unitId: inquiry.unitId, //
            totalNum: inquiry.totalNum, //
            purchasePrice: inquiry.purchasePrice,
            discount: inquiry.discount, //
            taxRate: inquiry.taxRate,
            totalMoney: inquiry.totalMoney,
            detailRemark: inquiry.detailRemark, //
            goodcode: inquiry.goodcode, //
            goodname: inquiry.goodname, //
            unitname: inquiry.unitname, //
            wId: inquiry.wId, //
            purPri: inquiry.purPri, //采购费用
            relatedOrder: inquiry.relatedOrder, //关联购货订单
            orderDetailId: inquiry.orderDetailId,
          });
        }
      });

      if (msgWId) {
        this.errorMessage(msgWId);
        return;
      }

      if (msgTotalNum) {
        this.errorMessage(msgTotalNum);
        return;
      }

      if (this.purchaseOrder.thisPayment && !this.purchaseOrder.accountId) {
        this.errorMessage("付款额不为空时，请选择结算账户");
        return;
      }

      if (details.length < 1) {
        this.errorMessage("商品信息不可以为空");
        return;
      }

      // console.log(details)
      const formdata = new FormData();
      formdata.append("purchaseOrder", JSON.stringify(this.purchaseOrder));
      formdata.append("purchaseOrderDetail", JSON.stringify(details));

      if (!this.purchaseOrder.id) {
        this.axios.post("/purchase/purchaseOrder/add", formdata).then((rs) => {
          if ((rs.data.code = 200)) {
            this.successMessage("添加成功");
            this.letNull();
          } else {
            this.errorMessage("添加失败");
          }
        });
      } else {
        this.axios
          .post("/purchase/purchaseOrder/update", formdata)
          .then((rs) => {
            if ((rs.data.code = 200)) {
              this.successMessage("修改成功");
              this.letNull();
            } else {
              this.errorMessage("修改失败");
            }
          });
      }
    },
    letNull() {
      this.effectiveDateRange = "";
      this.selectByIdDate = [];
      this.purchaseOrder = {
        id: "",
        proId: "",
        yid: "",
        accountId: "",
        deliveryMethodId: "",
        createDate: "",
        purPriSum: 0, //采购费用
        thisPayment: 0, //本次付款
        quantity: "",
        amount: "",
        status: "",
        remark: "",
        documentNumber: "",
        //已核销金额
        //
        proName: "",
        purType: 1,
        reviewStatus: "",
      };
      this.purchaseOrderDetail = [
        {
          id: "", // id
          numbering: "", // 购货单id
          unitId: "", // 单位Id
          totalNum: 1, // 数量
          maxTotalNum: "",
          discount: 0, // 折扣率
          detailRemark: "", // 详细备注
          imagename: null, // 商品图片名称
          goodcode: "", // 商品编号
          brandName: "", // 品牌名称
          origin: "", // 产地
          goodname: "", // 商品名称
          categoryName: "", // 商品类别
          unitname: "", // 单位名称
          wId: "", // 仓库Id
          availableStock: "", // 可用库存
          purchasePrice: 0, //购货单价
          totalPrice: 0, // 含税单价
          taxRate: 0, // 税率
          tax: 0, // 税额
          totalMoney: 0, // 价税合计
          discountAmount: 0, // 折扣额
          discountNoRate: 10, // 折扣(折)
          amount: 0, // 金额
          purPri: 0, //采购费用
          relatedOrder: "", //关联购货订单
          orderDetailId: "",
        },
      ];
    },
    goods(index) {
      this.index = index;
      this.goodsShow = true;
    },
    yesGoods() {
      this.goodsShow = false;
      var selectedGoods = this.$refs.chooseGoods.selectionList;
      console.log(selectedGoods);
      if (selectedGoods.length > 0 && this.index !== "") {
        var currentIndex = parseInt(this.index);
        // 插入第一条数据到指定的currentIndex行
        Object.keys(selectedGoods[0]).forEach((key) => {
          this.$set(
            this.purchaseOrderDetail[currentIndex],
            key,
            selectedGoods[0][key]
          );
        });

        // 处理剩余的数据
        for (let i = 1; i < selectedGoods.length; i++) {
          // 在当前行后新增一行
          this.addRow(currentIndex + i - 1);

          // 插入数据到新增的行
          Object.keys(selectedGoods[i]).forEach((key) => {
            this.$set(
              this.purchaseOrderDetail[currentIndex + i],
              key,
              selectedGoods[i][key]
            );
          });
        }
      }
    },
    addRow(index) {
      const newRow = {
        id: "", // id
        numbering: "", // 购货单id
        unitId: "", // 单位Id
        totalNum: 1, // 数量
        maxTotalNum: "",
        discount: 0, // 折扣率
        detailRemark: "", // 详细备注
        imagename: null, // 商品图片名称
        goodcode: "", // 商品编号
        brandName: "", // 品牌名称
        origin: "", // 产地
        goodname: "", // 商品名称
        categoryName: "", // 商品类别
        unitname: "", // 单位名称
        wId: "", // 仓库Id
        availableStock: "", // 可用库存
        purchasePrice: 0, //购货单价
        totalPrice: 0, // 含税单价
        taxRate: 0, // 税率
        tax: 0, // 税额
        totalMoney: 0, // 价税合计
        discountAmount: 0, // 折扣额
        discountNoRate: 10, // 折扣(折)
        amount: 0, // 金额
        purPri: 0, //采购费用
        relatedOrder: "", //关联购货订单
        orderDetailId: "",
      };

      this.purchaseOrderDetail.splice(index + 1, 0, newRow);
    },
    reduceRow(index) {
      if (this.purchaseOrderDetail.length > 1) {
        this.purchaseOrderDetail.splice(index, 1);
      }
    },
    yes() {
      this.dialogShow = false;
      var list = this.$refs.choosePro.selectionList;
      this.purchaseOrder.proName = list[0].providerName;
      this.purchaseOrder.proId = list[0].providerId;
    },
    selectEm() {
      this.axios({
        url: "/info/employee/listAll",
      }).then((rs) => {
        this.employee = rs.data.list;
      });
    },
    selctSH() {
      this.axios
        .get("/info/storeHouse/getAllStore", {
          params: {
            cId: 1,
          },
        })
        .then((rs) => {
          this.storeHouse = rs.data.storeList;
        });
    },
    getAccounts: function () {
      this.axios({
        url: "/info/account/selectAll",
        params: {},
      }).then((rs) => {
        console.log(rs);
        this.accounts = rs.data.accounts;
      });
    },
    selectByOrderId() {
      this.axios({
        url: "/purchase/order/selectById",
        params: {
          orderId: this.orderId,
        },
      }).then((rs) => {
        let order = rs.data.order;

        console.log(order);

        // 将selectByIdDate中的其他属性赋给purchaseOrder
        this.purchaseOrder = {
          id: "",
          proId: order.proId,
          yid: order.yid,
          accountId: "",
          deliveryMethodId: order.deliveryMethodId,
          createDate: order.createDate,
          purPriSum: 0, //采购费用
          thisPayment: 0, //本次付款
          quantity: order.quantity,
          amount: order.amount,
          status: order.status,
          remark: order.remark,
          documentNumber: "",
          //已核销金额
          proName: order.proName,
          purType: 1,
          //购货订单生成购货单
          orderNumber: order.documentNumber, //关联购货订单号
          reviewStatus: "",
        };
        this.purchaseOrderDetail = [];
        // 询价详情列表
        this.purchaseOrderDetail = order.orderDetails
          .filter((detail) => {
            if (!detail.purOrderNumQuantity) {
              detail.purOrderNumQuantity = 0;
            }
            return detail.totalNum - detail.purOrderNumQuantity > 0;
          })
          .map((detail) => ({
            detailRemark: detail.detailRemark,
            imagename: detail.imagename,
            goodcode: detail.goodcode,
            brandName: detail.brandName,
            goodname: detail.goodname,
            categoryName: detail.categoryName,
            unitname: detail.unitname,
            deliveryDateDetail: detail.deliveryDateDetail,
            wId: detail.wId,
            availableStock: detail.availableStock,
            purchasePrice: detail.purchasePrice,
            taxRate: detail.taxRate,
            totalMoney: detail.totalMoney,
            id: "", // id
            numbering: "", // 购货单id
            unitId: detail.unitId,
            totalNum: detail.totalNum - detail.purOrderNumQuantity,
            discount: detail.discount,
            origin: "", // 产地
            totalPrice: 0, // 含税单价
            tax: 0, // 税额
            discountAmount: 0, // 折扣额
            discountNoRate: 10, // 折扣(折)
            amount: 0, // 金额
            purPri: 0, //采购费用
            relatedOrder: order.documentNumber, //关联购货订单
            orderDetailId: detail.orderDetailId,
            maxTotalNum: detail.totalNum - detail.purOrderNumQuantity,
          }));

        this.purchaseOrderDetail.forEach((row) => {
          this.calculateRow(row);
        });
      });
    },
    selectById: function () {
      this.axios({
        url: "/purchase/purchaseOrder/selectById",
        params: {
          id: this.purchaseOrder.id,
        },
      }).then((rs) => {
        this.selectByIdDate = rs.data.purchaseOrder;
        console.log(this.selectByIdDate);

        // 清空purchaseOrderDetail数组，以便重新赋值
        this.purchaseOrderDetail = [];

        // 将selectByIdDate中的其他属性赋给purchaseOrder
        this.purchaseOrder = {
          id: this.selectByIdDate.id,
          proId: this.selectByIdDate.proId,
          yid: this.selectByIdDate.yid,
          accountId: this.selectByIdDate.accountId,
          deliveryMethodId: this.selectByIdDate.deliveryMethodId,
          createDate: this.selectByIdDate.createDate,
          purPriSum: this.selectByIdDate.purPriSum,
          thisPayment: this.selectByIdDate.thisPayment,
          quantity: this.selectByIdDate.quantity,
          amount: this.selectByIdDate.amount,
          status: this.selectByIdDate.status,
          remark: this.selectByIdDate.remark,
          documentNumber: this.selectByIdDate.documentNumber,
          proName: this.selectByIdDate.proName,
          purType: this.selectByIdDate.purType,
          reviewStatus: this.selectByIdDate.reviewStatus,
        };

        // 询价详情列表
        this.purchaseOrderDetail = this.selectByIdDate.purchaseOrderDetails.map(
          (detail) => {
            return {
              id: detail.id,
              numbering: detail.numbering,
              unitId: detail.unitId,
              totalNum: detail.totalNum,
              maxTotalNum: "",
              discount: detail.discount,
              detailRemark: detail.detailRemark,
              imagename: detail.imagename,
              goodcode: detail.goodcode,
              brandName: detail.brandName,
              origin: "",
              goodname: detail.goodname,
              categoryName: detail.categoryName,
              unitname: detail.unitname,
              wId: detail.wId,
              availableStock: detail.availableStock,
              purchasePrice: detail.purchasePrice,
              totalPrice: 0,
              taxRate: detail.taxRate,
              tax: 0,
              totalMoney: detail.totalMoney,
              discountAmount: 0,
              discountNoRate: 10,
              amount: 0,
              purPri: detail.purPri, //采购费用
              relatedOrder: detail.relatedOrder, //关联购货订单
              orderDetailId: "",
            };
          }
        );

        this.purchaseOrderDetail.forEach((row) => {
          this.calculateRow(row);
        });
      });
    },
    selectByCode() {
      this.axios({
        url: "/purchase/purchaseOrder/selectByCode",
        params: {
          documentNumber: this.purchaseOrder.documentNumber,
        },
      }).then((rs) => {
        this.selectByIdDate = rs.data.purchaseOrder;
        console.log(this.selectByIdDate);

        // 清空purchaseOrderDetail数组，以便重新赋值
        this.purchaseOrderDetail = [];

        // 将selectByIdDate中的其他属性赋给purchaseOrder
        this.purchaseOrder = {
          id: this.selectByIdDate.id,
          proId: this.selectByIdDate.proId,
          yid: this.selectByIdDate.yid,
          accountId: this.selectByIdDate.accountId,
          deliveryMethodId: this.selectByIdDate.deliveryMethodId,
          createDate: this.selectByIdDate.createDate,
          purPriSum: this.selectByIdDate.purPriSum,
          thisPayment: this.selectByIdDate.thisPayment,
          quantity: this.selectByIdDate.quantity,
          amount: this.selectByIdDate.amount,
          status: this.selectByIdDate.status,
          remark: this.selectByIdDate.remark,
          documentNumber: this.selectByIdDate.documentNumber,
          proName: this.selectByIdDate.proName,
          purType: this.selectByIdDate.purType,
          reviewStatus: this.selectByIdDate.reviewStatus,
        };

        // 询价详情列表
        this.purchaseOrderDetail = this.selectByIdDate.purchaseOrderDetails.map(
          (detail) => {
            return {
              id: detail.id,
              numbering: detail.numbering,
              unitId: detail.unitId,
              totalNum: detail.totalNum,
              maxTotalNum: "",
              discount: detail.discount,
              detailRemark: detail.detailRemark,
              imagename: detail.imagename,
              goodcode: detail.goodcode,
              brandName: detail.brandName,
              origin: "",
              goodname: detail.goodname,
              categoryName: detail.categoryName,
              unitname: detail.unitname,
              wId: detail.wId,
              availableStock: detail.availableStock,
              purchasePrice: detail.purchasePrice,
              totalPrice: 0,
              taxRate: detail.taxRate,
              tax: 0,
              totalMoney: detail.totalMoney,
              discountAmount: 0,
              discountNoRate: 10,
              amount: 0,
              purPri: detail.purPri, //采购费用
              relatedOrder: detail.relatedOrder, //关联购货订单
              orderDetailId: "",
            };
          }
        );

        this.purchaseOrderDetail.forEach((row) => {
          this.calculateRow(row);
        });
      });
    },
  },
  created() {
    this.selectEm();
    this.selctSH();
    this.getAccounts();

    this.purchaseOrder.id = this.$route.query.id;
    if (this.purchaseOrder.id) {
      this.selectById();
    }

    this.orderId = this.$route.query.orderId;

    if (this.orderId) {
      this.selectByOrderId();
    }

    this.taskId = this.$route.query.taskId;
    this.purchaseOrder.documentNumber = this.$route.query.billCode;

    if (this.taskId) {
      this.selectByCode();
    }
  },
};
</script>

<style scoped>
#order {
  width: 100%;
  height: 100%;
}

.order-top {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  width: calc(100% - 20px);
  padding-left: 20px;
  font-size: 13px;
}

.custom-radio .el-radio__label {
  display: none;
}

.form-group {
  display: flex;
  align-items: center;
  margin-right: 20px; /* 组间距 */
  margin-top: 10px;
}

.el-autocomplete-suggestion__item {
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.order-content {
  width: 100%;
}

.spanRed {
  color: rgb(255, 98, 93);
  margin-right: 8px;
}

.el-input,
.el-button {
  font-size: 13px;
}

.el-select,
.el-date-picker {
  margin-left: 10px;
}

.return {
  margin: 5px 0 0 15px;
}

/* 合计行整体样式修改开始 */
.el-table /deep/ .el-table__footer-wrapper tbody td {
  background-color: #fff1d4;
}

.el-table /deep/ .el-table__body tr:hover > td {
  background-color: #fff1d4;
}
</style>